<route lang="json5">
{
  style: {
    navigationBarTitleText: '礼物记录'
  }
}
</route>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'
import { useToast } from 'wot-design-uni'
import dayjs from 'dayjs'
import type { Gift } from '@/types/couple'

defineOptions({ name: 'Gifts' })

const coupleStore = useSupabaseCoupleStore()
const { success: showSuccess, error: showError } = useToast()

const showAdd = ref(false)
const showEdit = ref(false)
const showDatePicker = ref(false)
const showEditDatePicker = ref(false)
const editingId = ref<string | null>(null)
const form = ref<Partial<Gift>>({
  title: '',
  description: '',
  giver: '',
  receiver: '',
  occasion: '',
  date: dayjs().format('YYYY-MM-DD'),
  value: undefined,
  photos: [],
  significance: '',
})

const editForm = ref<Partial<Gift>>({
  title: '',
  description: '',
  giver: '',
  receiver: '',
  occasion: '',
  date: dayjs().format('YYYY-MM-DD'),
  value: undefined,
  photos: [],
  significance: '',
})

// 用于日期选择器的临时变量（时间戳）
const tempDate = ref(Date.now())

const occasions = [
  { label: '生日', value: '生日' },
  { label: '纪念日', value: '纪念日' },
  { label: '节日', value: '节日' },
  { label: '惊喜', value: '惊喜' },
  { label: '道歉', value: '道歉' },
  { label: '其他', value: '其他' },
]

// 处理日期选择
function handleDateConfirm() {
  const val = dayjs(tempDate.value).format('YYYY-MM-DD')
  form.value.date = val
  showDatePicker.value = false
}

function handleEditDateConfirm() {
  const val = dayjs(tempDate.value).format('YYYY-MM-DD')
  editForm.value.date = val
  showEditDatePicker.value = false
}

// 格式化日期用于弹窗显示
function formatDateForCell(date: string | Date): string {
  if (!date)
    return '请选择日期'
  return dayjs(date).format('YYYY-MM-DD')
}

// 选择本地图片并立即预览（小程序）
async function handleChooseImage(record: Partial<Gift>) {
  const currentPhotosCount = record.photos?.length || 0
  if (currentPhotosCount >= 9) {
    showError('最多只能上传9张图片')
    return
  }
  try {
    const resMedia: any = await uni.chooseMedia({
      count: 9 - currentPhotosCount,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
    })
    if (!record.photos)
      record.photos = []
    const paths = (resMedia?.tempFiles || []).map((f: any) => f.tempFilePath)
    ;(record.photos as any[]).push(...paths)
  }
  catch (e) {
    console.log('选择图片取消/失败', e)
  }
}

function handleRemoveImage(record: Partial<Gift>, index: number) {
  record.photos?.splice(index, 1)
}

function getPhotoUrl(photo: any): string {
  return photo
}

function handlePreviewImage(photos: any[], current: any) {
  const urls = photos.map(p => getPhotoUrl(p))
  const currentUrl = getPhotoUrl(current)
  uni.previewImage({ urls, current: currentUrl })
}

// 压缩（小程序）
async function compressImageMp(path: string, quality = 70): Promise<string> {
  return await new Promise<string>((resolve, reject) => {
    uni.showLoading({ title: '压缩中...', mask: true })
    uni.compressImage({
      src: path,
      quality,
      success: (res) => {
        const out = (res as any).tempFilePath || path
        resolve(out)
      },
      fail: reject,
    })
  })
}

// 上传到 Supabase images（小程序，REST）
async function uploadPhotos(photos: any[]): Promise<string[]> {
  uni.showLoading({ title: '上传中...', mask: true })
  const total = photos.length
  let finished = 0
  const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
  const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY

  const uploadPromises = photos.map(async (photo) => {
    const photoPath = photo as string
    const compressedPath = await compressImageMp(photoPath, 70)
    const ext = compressedPath.substring(compressedPath.lastIndexOf('.')) || photoPath.substring(photoPath.lastIndexOf('.'))
    const fileName = `gift-${Date.now()}${ext}`

    const uploadUrl = `${supabaseUrl}/storage/v1/object/images/${encodeURIComponent(fileName)}`
    await new Promise<void>((resolve, reject) => {
      const task = uni.uploadFile({
        url: uploadUrl,
        filePath: compressedPath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${supabaseAnonKey}`,
          'Cache-Control': '3600',
          'x-upsert': 'false',
        },
        success: (res) => {
          if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
            finished += 1
            uni.showLoading({ title: `上传中 ${finished}/${total}`, mask: true })
            resolve()
          }
          else {
            reject(new Error(`上传失败: ${res.statusCode}`))
          }
        },
        fail: reject,
      })
      task.onProgressUpdate?.((p) => {
        uni.showLoading({ title: `上传中 ${p.progress}%`, mask: true })
      })
    })
    return `${supabaseUrl}/storage/v1/object/public/images/${encodeURIComponent(fileName)}`
  })
  const result = await Promise.all(uploadPromises)
  uni.hideLoading()
  return result
}

async function submit() {
  if (!form.value.title)
    return showError('请输入礼物名称')
  try {
    const uploadedPhotos = await uploadPhotos(form.value.photos || [])
    await coupleStore.addGift({
      title: form.value.title!,
      description: form.value.description || '',
      giver: form.value.giver || coupleStore.profile?.user1.id || 'user1',
      receiver: form.value.receiver || coupleStore.profile?.user2.id || 'user2',
      occasion: form.value.occasion || '其他',
      date: form.value.date || dayjs().format('YYYY-MM-DD'),
      value: form.value.value,
      photos: uploadedPhotos,
      significance: form.value.significance || '',
    })
    showAdd.value = false
    form.value = { title: '', description: '', giver: '', receiver: '', occasion: '', date: dayjs().format('YYYY-MM-DD'), value: undefined, photos: [], significance: '' }
    showSuccess('礼物记录已添加')
  }
  catch (e) {
    showError('添加失败，请重试')
  }
  finally {
    uni.hideLoading()
  }
}

// 编辑相关函数
function openActions(gift: Gift) {
  uni.showActionSheet({
    itemList: ['编辑', '删除', '取消'],
    success: (res) => {
      if (res.tapIndex === 0)
        beginEdit(gift)
      else if (res.tapIndex === 1)
        confirmRemove(gift)
    },
  })
}

function beginEdit(gift: Gift) {
  editingId.value = gift.id
  editForm.value = { ...gift }
  // 设置编辑时的时间戳
  tempDate.value = gift.date ? dayjs(gift.date).valueOf() : Date.now()
  showEdit.value = true
}

function closeEdit() {
  showEdit.value = false
  editingId.value = null
  editForm.value = {
    title: '',
    description: '',
    giver: '',
    receiver: '',
    occasion: '',
    date: dayjs().format('YYYY-MM-DD'),
    value: undefined,
    photos: [],
    significance: '',
  }
}

async function submitEdit() {
  if (!editingId.value || !editForm.value.title)
    return showError('请输入礼物名称')

  try {
    // 处理图片：区分已上传的图片和新选择的本地图片
    // 已上传的图片应该是以 supabase.co 开头的URL
    const existingPhotos = editForm.value.photos?.filter(photo =>
      typeof photo === 'string' && photo.includes('supabase.co'),
    ) || []

    // 新选择的图片可能是 tempFilePath 或 http://tmp/ 格式
    const newLocalPhotos = editForm.value.photos?.filter(photo =>
      typeof photo === 'string' && !photo.includes('supabase.co'),
    ) || []

    let uploadedPhotos: string[] = []
    if (newLocalPhotos.length > 0) {
      uploadedPhotos = await uploadPhotos(newLocalPhotos)
    }

    const allPhotos = [...existingPhotos, ...uploadedPhotos]

    await coupleStore.updateGift(editingId.value, {
      title: editForm.value.title,
      description: editForm.value.description || '',
      giver: editForm.value.giver || coupleStore.profile?.user1.id || 'user1',
      receiver: editForm.value.receiver || coupleStore.profile?.user2.id || 'user2',
      occasion: editForm.value.occasion || '其他',
      date: editForm.value.date || dayjs().format('YYYY-MM-DD'),
      value: editForm.value.value,
      photos: allPhotos,
      significance: editForm.value.significance || '',
    })

    showEdit.value = false
    editingId.value = null
    showSuccess('礼物记录已更新')
  }
  catch (e) {
    console.error('编辑失败:', e)
    showError('更新失败，请重试')
  }
  finally {
    uni.hideLoading()
  }
}

function confirmRemove(gift: Gift) {
  uni.showModal({
    title: '删除确认',
    content: `确定删除"${gift.title}"吗？`,
    success: async ({ confirm }) => {
      if (confirm) {
        try {
          await coupleStore.removeGift(gift.id)
          showSuccess('已删除')
        }
        catch (e) {
          showError('删除失败，请重试')
        }
      }
    },
  })
}

const gifts = computed(() => coupleStore.gifts)

onMounted(() => {
  if (!coupleStore.profile) {
    coupleStore.initProfile()
  }
})
</script>

<template>
  <view class="gifts-container">
    <!-- 添加按钮 -->
    <view class="toolbar">
      <wd-button type="primary" @click="showAdd = true">
        <wd-icon name="add" size="16px" /> 记录礼物
      </wd-button>
    </view>

    <!-- 礼物列表 -->
    <view class="list">
      <view v-for="item in gifts" :key="item.id" class="card">
        <view class="hd">
          <view class="title">
            {{ item.title }}
          </view>
          <view class="occasion">
            {{ item.occasion }}
          </view>
          <view class="actions">
            <wd-button size="small" plain @click="openActions(item)">
              更多
            </wd-button>
          </view>
        </view>
        <view class="meta">
          <view class="date">
            {{ dayjs(item.date).format('YYYY年MM月DD日') }}
          </view>
          <view v-if="item.value" class="value">
            ¥{{ item.value }}
          </view>
        </view>
        <view v-if="item.description" class="desc">
          {{ item.description }}
        </view>
        <view v-if="item.significance" class="significance">
          <text class="label">意义：</text>{{ item.significance }}
        </view>

        <view v-if="item.photos?.length" class="photos">
          <image
            v-for="(url, idx) in item.photos" :key="idx" :src="url" class="photo" mode="aspectFill"
            @click="handlePreviewImage(item.photos, url)"
          />
        </view>
      </view>

      <view v-if="gifts.length === 0" class="empty">
        <wd-icon name="gift" size="64px" color="#ccc" />
        <text class="tip">还没有礼物记录，点击上方按钮开始记录吧</text>
      </view>
    </view>

    <!-- 添加弹窗 -->
    <wd-popup v-model="showAdd" position="bottom" :safe-area-inset-bottom="true">
      <view class="dialog">
        <view class="dialog-hd">
          <view class="title">
            记录礼物
          </view>
          <wd-icon name="close" @click="showAdd = false" />
        </view>
        <view class="dialog-bd">
          <wd-cell-group>
            <wd-input v-model="form.title" label="礼物名称" placeholder="例如：玫瑰花/手表" required />
            <wd-picker v-model="form.occasion" label="场合" :columns="occasions" />
            <wd-cell title="日期" :value="formatDateForCell(form.date)" is-link @click="showDatePicker = true; tempDate = form.date ? dayjs(form.date).valueOf() : Date.now()" />
            <wd-input v-model="form.value" label="价值" type="number" placeholder="礼物价值（可选）" />
            <wd-textarea v-model="form.description" label="描述" placeholder="礼物描述（可选）" :auto-height="true" />
            <wd-textarea v-model="form.significance" label="意义" placeholder="这份礼物的特殊意义（可选）" :auto-height="true" />
          </wd-cell-group>

          <!-- 照片上传 -->
          <view class="photo-uploader">
            <view class="up-title">
              添加照片
            </view>
            <view class="photo-grid">
              <view v-for="(photo, index) in form.photos" :key="index" class="photo-item">
                <image :src="getPhotoUrl(photo)" mode="aspectFill" class="preview-img" @click="handlePreviewImage(form.photos, photo)" />
                <view class="remove-icon" @click="handleRemoveImage(form, index)">
                  <wd-icon name="close-bold" color="#fff" />
                </view>
              </view>
              <view v-if="(form.photos?.length || 0) < 9" class="add-photo-btn" @click="handleChooseImage(form)">
                <wd-icon name="add" size="36px" color="#ccc" />
              </view>
            </view>
          </view>
        </view>
        <view class="dialog-ft">
          <wd-button @click="showAdd = false">
            取消
          </wd-button>
          <wd-button type="primary" @click="submit">
            保存
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 编辑弹窗 -->
    <wd-popup v-model="showEdit" position="bottom" :safe-area-inset-bottom="true">
      <view class="dialog">
        <view class="dialog-hd">
          <view class="title">
            编辑礼物
          </view>
          <wd-icon name="close" @click="closeEdit" />
        </view>
        <view class="dialog-bd">
          <wd-cell-group>
            <wd-input v-model="editForm.title" label="礼物名称" placeholder="例如：玫瑰花/手表" required />
            <wd-picker v-model="editForm.occasion" label="场合" :columns="occasions" />
            <wd-cell title="日期" :value="formatDateForCell(editForm.date)" is-link @click="showEditDatePicker = true; tempDate = editForm.date ? dayjs(editForm.date).valueOf() : Date.now()" />
            <wd-input v-model="editForm.value" label="价值" type="number" placeholder="礼物价值（可选）" />
            <wd-textarea v-model="editForm.description" label="描述" placeholder="礼物描述（可选）" :auto-height="true" />
            <wd-textarea v-model="editForm.significance" label="意义" placeholder="这份礼物的特殊意义（可选）" :auto-height="true" />
          </wd-cell-group>

          <!-- 照片上传 -->
          <view class="photo-uploader">
            <view class="up-title">
              编辑照片
            </view>
            <view class="photo-grid">
              <view v-for="(photo, index) in editForm.photos" :key="index" class="photo-item">
                <image :src="getPhotoUrl(photo)" mode="aspectFill" class="preview-img" @click="handlePreviewImage(editForm.photos, photo)" />
                <view class="remove-icon" @click="handleRemoveImage(editForm, index)">
                  <wd-icon name="close-bold" color="#fff" />
                </view>
              </view>
              <view v-if="(editForm.photos?.length || 0) < 9" class="add-photo-btn" @click="handleChooseImage(editForm)">
                <wd-icon name="add" size="24px" color="#ccc" />
              </view>
            </view>
          </view>
        </view>
        <view class="dialog-ft">
          <wd-button @click="closeEdit">
            取消
          </wd-button>
          <wd-button type="primary" @click="submitEdit">
            保存
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 日期选择器 -->
    <wd-popup v-model="showDatePicker" position="bottom">
      <wd-datetime-picker-view
        v-model="tempDate"
        type="date"
      />
      <view class="picker-actions">
        <wd-button @click="showDatePicker = false">
          取消
        </wd-button>
        <wd-button type="primary" @click="handleDateConfirm">
          确定
        </wd-button>
      </view>
    </wd-popup>

    <!-- 编辑日期选择器 -->
    <wd-popup v-model="showEditDatePicker" position="bottom">
      <wd-datetime-picker-view
        v-model="tempDate"
        type="date"
      />
      <view class="picker-actions">
        <wd-button @click="showEditDatePicker = false">
          取消
        </wd-button>
        <wd-button type="primary" @click="handleEditDateConfirm">
          确定
        </wd-button>
      </view>
    </wd-popup>

    <wd-toast />
  </view>
</template>

<style scoped lang="scss">
.gifts-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 30% 20%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 70% 80%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
  }
}
.toolbar {
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
}
.list {
  padding: 12px 16px;
}
.card {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.hd {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}
.title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
}
.occasion {
  font-size: 12px;
  color: #fff;
  background: linear-gradient(135deg, #ff69b4, #ff1493);
  padding: 2px 8px;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(255, 105, 180, 0.3);
  margin: 0 8px;
}
.actions {
  margin-left: auto;
}
.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 6px 0;
}
.date {
  font-size: 12px;
  color: #666;
}
.value {
  font-size: 12px;
  color: #ff69b4;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(255, 105, 180, 0.3);
}
.desc,
.significance {
  font-size: 14px;
  color: #555;
  line-height: 1.5;
  margin: 8px 0;
}
.label {
  color: #999;
  font-size: 12px;
}
.photos {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 6px;
  margin-top: 8px;
}
.photo {
  width: 100%;
  height: 90px;
  border-radius: 8px;
}
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #999;
}
.tip {
  margin-top: 8px;
  font-size: 12px;
}
.dialog {
  background: #fff;
  border-radius: 16px 16px 0 0;
}
.dialog-hd {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}
.dialog-bd {
  padding: 12px 16px;
}
.upload {
  margin-top: 8px;
}
.up-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
.dialog-ft {
  display: flex;
  gap: 10px;
  padding: 12px 16px;
  border-top: 1px solid #eee;
}

/* 照片上传区域样式（对话框内预览）*/
.photo-uploader {
  margin-top: 8px;
}
.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}
.photo-item {
  position: relative;
  width: 100%;
  padding-top: 100%;
  border-radius: 8px;
  overflow: hidden;
  background: #f7f7f7;
}
.preview-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.remove-icon {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  align-items: center;
  justify-content: center;
}
.add-photo-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100px;
  border-radius: 8px;
  border: 1px dashed #ddd;
  background: #fafafa;
}

.picker-actions {
  display: flex;
  gap: 12px;
  padding: 20px;
  background: white;
  border-top: 1px solid #eee;
}
</style>
